<?php


namespace api\common\yueke;


use app\common\service\FunctionService;
use cmf\controller\AdminBaseController;
use app\common\service\CurlService;
use think\Request;
use think\Controller;
use think\Cache;
ini_set('memory_limit', '1280M');
/**
 * 约克api
 * Class YuekeController
 * @package app\admin\controller
 */
class YuekeController extends Controller
{
    private $appid = 'E7JFNAYUY3DJ';  // appid

    private $secret = 'OPH1YMJ2JAWJ9NSE'; // secret

    const API = 'https://event.inh5.cn/yorkqyinterfaceapi/public/';

    const API_GETTOKEN = 1; // 获取token
    const API_GETRECORD = 2; // 获取报备信息
    const API_ADDRECORD = 3; // 安装信息接口
    const API_GETJXSSHOP = 4; // 获取经销商、门店人员信息

    const API_GETRECORDCS = 5; // 测试方法获取获取报备信息


    const API_GETAZSORDER = 6;  //测试获取安装商单子
    const API_POSTAZSPARAM = 7;  //传递安装商单子
    const API_POSTLSSJPLTB= 8;  //批量处理以前的数据

    const API_GETAZDSHUJU=9;  //获取安装单过渡

    const API_GETAZDSHIJIAN=10;   //获取安装单时间根据报备单号

    const API_GETAZDNEIJI=11;   //传输内机信息
    const API_GETAZDNEIWAI=12;   //传输内外机信息
    const API_GETKUAORDER=13;
    protected $token; // 24小时过期
    protected $apiUrl = [
        1 => 'App.Token.GetToken',
        2 => 'App.RecordData.GetYorkRecordData',
        3 => 'App.RecordData.AddYorkRecordData',
        4 => 'App.Externalapp.GetYorkqyDealerAndShopUser',
        5 => 'App.RecordData.GetYorkRecordData',

        6 => 'App.RecordData.GetYorkRecordData',
        7 => 'App.RecordData.AddRecordInstallation',
        8 => 'App.RecordData.AddInstallationAllData',

        9=>'App.RecordData.GetYorkRecordData',

        10=>'App.RecordData.GetYorkRecordData',
        11=>'App.RecordData.WxAddRecordConcealedWork',
        12=>'App.RecordData.WxAddRecordData',
        13=>'App.RecordData.GetTransregionalYorkRecordData',
    ];

    /**
     * 获取token
     */
    public function getToken(){
        $param = $this->buildParam($this->apiUrl[self::API_GETTOKEN]);
        $res = CurlService::curlRequest(self::API,$param);
        $res = json_decode($res,true);
        if ($res['ret'] != 200){
            // $msg = $res['msg'];
            return false;
        }
        $token=$res['data']['access_token'];
        /*$token = Cache::get('yueke_token');
        if (!$token){
            $res = CurlService::curlRequest(self::API,$param);
            $res = json_decode($res,true);
            if ($res['ret'] != 200){
                // $msg = $res['msg'];
                return false;
            }
            Cache::set('yueke_token',$res['data']['access_token'],$res['data']['expires_in']-100);
            return $res['data']['access_token'];
        }*/
        return $token;
    }

    /**
     * 获取经销商、门店人员
     */
    public function getJxsAndShop(){
        $param = $this->buildParam($this->apiUrl[self::API_GETJXSSHOP]);
        $url = self::API.'?'.http_build_query($param);
        $res = $this->post_curls($url, ['access_token' => $this->getToken()]);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
//                $this->getJxsAndShop();
                $res = $this->post_curls($url, ['access_token' => $this->getToken()]);
                $res = json_decode($res, true);
                $data = $this->getYuekeUser(@$res['data']['DATALIST']);
                return $data;
            }else{
                return false;
            }
        }else{
            $data = $this->getYuekeUser(@$res['data']['DATALIST']);
            return $data;
        }

//        dump($data);
    }

    public function getYuekeUser($data){
        $data = FunctionService::arraykeyToLower($data);
        foreach ($data as $k=>$v){
            unset($data[$k]['user_position']);
            $data[$k]['yg_bm'] = '';
            $data[$k]['bm_code'] = $v['jxs_code'];
            $data[$k]['gw_cp'] = $v['gw'];
            $data[$k]['email'] = '';
            // $data[$k]['status'] = 2;
        }
        return $data;
    }

    /**
     * 获取报备信息
     */
    public function getBaobeiInfo($mobile = '12222222222',$gw = 1){
        if(config('is_ceshi'))
        {
            $param = $this->buildParam($this->apiUrl[self::API_GETRECORDCS]);//测试
        }else{
            $param = $this->buildParam($this->apiUrl[self::API_GETRECORD]);
        }
        $url = self::API.'?'.http_build_query($param);
        $post['access_token'] = $this->getToken();
        $post['USER_PHONE'] = $mobile; // 手机号码
        $post['ZW'] = $gw; // 岗位
        $res = $this->post_curls($url, $post);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
//                $this->getBaobeiInfo($mobile);
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data']['data'];
            }else{
                return false;
            }
        }else{
            return $res['data']['data'];
        }

    }
    /**/
    public function getDanjuOrder(){
        $param = $this->buildParam($this->apiUrl[self::API_GETAZDSHUJU]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data'];
            }else{
                return false;
            }
        }else{
            return $res['data']['data'];
        }
    }
    //安装单内机数据推送门店
    public function PushAzdNeiData($Azdata=''){
        $param = $this->buildParam($this->apiUrl[self::API_GETAZDNEIJI]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $data=array_merge($Azdata,$data);
        $res = $this->post_curls($url, $data);
        $res=json_decode($res,true);
        if($res['data']['TYPE']=='S'){
            return true;
        }
        return false;
    }
    //安装单内外机数据推送门店
    public function PushAzdNeiWaiData($Azdata=''){
        $param = $this->buildParam($this->apiUrl[self::API_GETAZDNEIWAI]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $data=array_merge($Azdata,$data);
        $res = $this->post_curls($url, $data);
        $res=json_decode($res,true);


        if($res['data']['TYPE']=='S'){
            return true;
        }
        return false;
    }
    /*获取预约安装时间*/
    public function getazd_sj(){
        $param = $this->buildParam($this->apiUrl[self::API_GETAZDSHIJIAN]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data'];
            }else{
                return false;
            }
        }else{
            return $res['data']['data'];
        }
    }

    /**
     * 获取安装商的安装单数量
     */
    public function getAzsOrder(){
        $param = $this->buildParam($this->apiUrl[self::API_GETAZSORDER]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $data['BRAND'] = 1;
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data'];
            }else{
                return false;
            }
        }else{
            return $res['data']['data'];
        }
    }
    /*获取跨区安装单*/
    public function getKuaOrder(){
        $param = $this->buildParam($this->apiUrl[self::API_GETKUAORDER]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $data['BRAND'] = 1;
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data'];
            }else{
                return false;
            }
        }else{
            return $res['data']['data'];
        }
    }
    /*批量更改安装单数据*/
    public function lssjPltb($datas){
        $param = $this->buildParam($this->apiUrl[self::API_POSTLSSJPLTB]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $data['INSTALL_DATA']=$datas;
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data']['MSG'];
                // return $res['data']['MSG'];

            }else{
                return false;
            }
        }else{
            return $res['data']['MSG'];
            // return $res['data']['MSG'];
        }
    }
    /**
     * 传递安装单的状态
     */
    public function postAzsParam($bbdh){
        $param = $this->buildParam($this->apiUrl[self::API_POSTAZSPARAM]);//测试
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $data['RECORD_NO']=$bbdh;
        $data['INSTALL_STATUS']=2;
        $data['BRAND']=1;
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        print_r($res);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $post['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $post);
                $res = json_decode($res, true);
                return $res['data']['data'];
            }else{
                return false;
            }
        }else{
            return $res['data']['TYPE'];
        }
    }

    /**
     * 安装信息同步
     */
    public function addRecordData($data){
        $param = $this->buildParam($this->apiUrl[self::API_ADDRECORD]);
        $url = self::API.'?'.http_build_query($param);
        $data['access_token'] = $this->getToken();
        $res = $this->post_curls($url, $data);
        $res = json_decode($res, true);
        if ($res['ret'] != 200){
            if ($res['ret'] == 406){
                Cache::rm('yueke_token');
                $data['access_token'] = $this->getToken();
                $res = $this->post_curls($url, $data);
                $res = json_decode($res, true);
                if ($res['ret'] != 200){
                    return false;
                }
                return true;
            }else{
                return false;
            }
        }else{
            if ($res['data']['TYPE'] != 'S'){
                // todo 记录日志
                trace('安装单号：'.@$data['AZ_ON'].$res['data']['MSG'],'yueke');
                return false;
            }
            return true;
        }
    }

    /*
     * 公用参数
     */
    private function buildParam($url){
        $t = time();
        $param['s'] = $url;
        $param['sign'] = $this->getSign($t);
        $param['appid'] = $this->appid;
        $param['t'] = $t;
        return $param;
    }
    /*
     * 签名
     */
    private function getSign($t){
        $paramsNew = [];
        $paramsNew['appid'] = $this->appid;
        $paramsNew['t'] = $t;
        $paramsNew['secret'] = $this->secret;
        ksort($paramsNew);
        $paramsStrExceptSign = '';
        foreach ($paramsNew as $val)
        {
            $paramsStrExceptSign .= $val;
        }
        return substr(md5($paramsStrExceptSign), 4, 16);
    }

    public function post_curls($url, $post)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式

    }
}
